package com.imooc.long5zb.handler;

import com.imooc.long5zb.CheckUtil;
import com.imooc.long5zb.dao.MongoUserRepository;
import com.imooc.long5zb.entity.MongoUser;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

@Component
public class MongoUserHandler {

    private final MongoUserRepository repository;

    public MongoUserHandler(MongoUserRepository rep) {
        this.repository = rep;
    }

    /**
     * 得到所有用户
     * @param request
     * @return
     */
    public Mono<ServerResponse> getAllUser(ServerRequest request) {
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON_UTF8)
                .body(this.repository.findAll(), MongoUser.class);
    }

    /*public Mono<ServerResponse> getAllUser(ServerRequest request) {
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON_UTF8)
                .body(this.repository.findAll(), MongoUser.class);
    }*/

    /**
     * 创建用户
     * @param request
     * @return
     */
    public Mono<ServerResponse> createUser(ServerRequest request) {
        Mono<MongoUser> userMono = request.bodyToMono(MongoUser.class);

        return userMono.flatMap( user -> {
            CheckUtil.checkName(user.getName());
            return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON_UTF8)
                    .body(this.repository.save(user), MongoUser.class);
                }) ;
    }

    /**
     * 删除用户
     * @param request
     * @return
     */
    public Mono<ServerResponse> deleteUserById(ServerRequest request) {
        String id = request.pathVariable("id");

        return this.repository.findById(id).flatMap(
                user -> this.repository.delete(user)
                .then(ServerResponse.ok().build()).switchIfEmpty(ServerResponse.notFound().build())
        );
    }
}
